"use client"

import { useState, useEffect, useRef } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { CameraFeed } from "@/components/camera-feed_video"
import { Users, BookOpen } from "lucide-react"
import dynamic from 'next/dynamic'
const AudioPlayer = dynamic(() => import("@/components/audio-player").then(mod => mod.AudioPlayer), {
  ssr: false,
})

const classrooms = [
  { id: "room-101", name: "A101", status: "online", cameras: 2 },
  { id: "room-102", name: "A102", status: "online", cameras: 2 },
  { id: "room-103", name: "C103", status: "online", cameras: 2 },
  { id: "room-104", name: "C104", status: "offline", cameras: 2 },
  { id: "room-105", name: "D105", status: "online", cameras: 2 },
]

const initFlvPlayer = async (videoEl: HTMLVideoElement | null, url: string) => {
  try {
    const flvjs = await import("flv.js")
    const player = flvjs.createPlayer({
       type: "flv",
       url,
       isLive: true, // 标记为直播流
      autoCleanupSourceBuffer: true, // 自动清理过期帧
      autoCleanupMinBackwardDuration: 2, // 最小倒退时间（秒）
      autoCleanupMaxBackwardDuration: 5, // 最大倒退时间（秒）
      enableWorker: true, // 启用 Web Worker 解析数据
      enableStashBuffer: true, // 启用缓冲区处理乱序帧
      stashInitialSize: 128, // 初始加载大小（KB）
      fixAudioTimestampGap: true, // 自动修复音频时间戳间隙
      seekType: "range", // 直播推荐 range 模式
      enableStatisticsInfoReport: false, // 关闭统计信息上报 
      })
    player.attachMediaElement(videoEl)
    player.load()
    player.on(flvjs.Events.LOADING_COMPLETE, () => {
      player.play().catch(err => console.error("播放失败:", err))
    })
    player.on(flvjs.Events.ERROR, (errorType, errorDetail) => {
      console.error("播放器错误:", errorType, errorDetail)
    })
    return player
  } catch (error) {
    console.error("播放器初始化失败:", error)
    return null
  }
}

const destroyFlvPlayer = (player: any) => {
  if (player) player.destroy()
}
const audio_url = "http://172.21.151.121/live?port=8002&app=flv&stream=audio"
export function VideoMonitoring() {
  const [selectedRoom, setSelectedRoom] = useState(classrooms[0].id)
  const currentRoom = classrooms.find((room) => room.id === selectedRoom) || classrooms[0]
  const [mainCamera, setMainCamera] = useState<"student" | "content">("student")
  const [audioActive, setAudioActive] = useState(false)

  const videoRef1 = useRef<HTMLVideoElement | null>(null)
  const videoRef2 = useRef<HTMLVideoElement | null>(null)
  const player1 = useRef<any>(null)
  const player2 = useRef<any>(null)

  useEffect(() => {
    const loadPlayers = async () => {
      const url1 = "http://172.21.151.121/live?port=8002&app=flv&stream=test"
      const url2 = "http://172.21.151.121/live?port=8002&app=flv&stream=test"
      player1.current = await initFlvPlayer(videoRef1.current, url1)
      player2.current = await initFlvPlayer(videoRef2.current, url2)
    }

    if (typeof window !== "undefined") {
      loadPlayers()
    }

    return () => {
      destroyFlvPlayer(player1.current)
      destroyFlvPlayer(player2.current)
    }
  }, [mainCamera])

  const switchCameras = () => {
    setMainCamera((prev) => (prev === "student" ? "content" : "student"))
  }

  const pipRef = useRef<HTMLDivElement>(null)
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 })
  const [isDragging, setIsDragging] = useState(false)
  const startPos = useRef({ x: 0, y: 0 })

  const handleMouseDown = (e: React.MouseEvent) => {
    if (!pipRef.current) return
    const rect = pipRef.current.getBoundingClientRect()
    startPos.current = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    }
    setIsDragging(true)
  }

  useEffect(() => {
    if (!isDragging) return

    const handleMouseMove = (e: MouseEvent) => {
      const newX = e.clientX - startPos.current.x
      const newY = e.clientY - startPos.current.y
      setDragPosition({ x: newX, y: newY })
    }

    const handleMouseUp = () => setIsDragging(false)

    document.addEventListener("mousemove", handleMouseMove)
    document.addEventListener("mouseup", handleMouseUp)

    return () => {
      document.removeEventListener("mousemove", handleMouseMove)
      document.removeEventListener("mouseup", handleMouseUp)
    }
  }, [isDragging])

  useEffect(() => {
    const updateInitialPosition = () => {
      if (pipRef.current) {
        const width = pipRef.current.offsetWidth || 200
        const height = pipRef.current.offsetHeight || 112
        setDragPosition({
          x: window.innerWidth - width - 16,
          y: window.innerHeight - height - 16,
        })
      }
    }

    updateInitialPosition()
    window.addEventListener("resize", updateInitialPosition)
    return () => window.removeEventListener("resize", updateInitialPosition)
  }, [])

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    switchCameras()
  }

  return (
    <Card className="overflow-hidden">
      <CardHeader className="pb-3">
        <div className="flex flex-col justify-between gap-2 sm:flex-row sm:items-center">
          <div>
            <CardTitle>实时视频监测</CardTitle>
            <CardDescription>查看教室实时视频流</CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <Select value={selectedRoom} onValueChange={setSelectedRoom}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="选择教室" />
              </SelectTrigger>
              <SelectContent>
                {classrooms.map((room) => (
                  <SelectItem key={room.id} value={room.id} disabled={room.status === "offline"}>
                    {room.name} {room.status === "offline" && "(离线)"}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Badge variant={currentRoom.status === "online" ? "default" : "outline"}>
              {currentRoom.status === "online" ? "在线" : "离线"}
            </Badge>
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-0">
        <div className="p-6 md:p-10">
          <Card className="mb-6">
            <CardHeader className="pb-2">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                <CardTitle>摄像头监控</CardTitle>
                <div className="flex items-center gap-2">
                  <div
                    className={`flex items-center gap-1 px-3 py-1 rounded-md ${
                      mainCamera === "student" ? "bg-primary text-primary-foreground" : "bg-muted"
                    }`}
                    onClick={() => setMainCamera("student")}
                  >
                    <Users className="h-4 w-4" />
                    <span className="text-sm">学生监控</span>
                  </div>
                  <div
                    className={`flex items-center gap-1 px-3 py-1 rounded-md ${
                      mainCamera === "content" ? "bg-primary text-primary-foreground" : "bg-muted"
                    }`}
                    onClick={() => setMainCamera("content")}
                  >
                    <BookOpen className="h-4 w-4" />
                    <span className="text-sm">黑板/PPT监控</span>
                  </div>
                </div>
              </div>
              <CardDescription className="pt-2">点击任意摄像头画面可切换主次显示</CardDescription>
            </CardHeader>

            <CardContent>
              {/* 主视频区域 */}
              <div className="relative aspect-[16/9] w-full rounded-md overflow-hidden bg-muted">
                <div className="w-full h-full" onClick={handleClick}>
                  <CameraFeed
                    videoRef={mainCamera === "student" ? videoRef1 : videoRef2}
                    networkError={false}
                    type={mainCamera}
                    isActive={true}
                    className="w-full h-full"
                    isPrimary={true}
                    pipMode={false}
                    onSwitchCamera={switchCameras}
                  />
                </div>

                {/* PIP */}
                <div
                  ref={pipRef}
                  style={{
                    left: `${dragPosition.x}px`,
                    top: `${dragPosition.y}px`,
                  }}
                  className="fixed w-1/5 aspect-[16/9] rounded-md overflow-hidden border-2 border-white shadow-lg cursor-grab active:cursor-grabbing hover:border-primary transition-colors"
                  onMouseDown={handleMouseDown}
                >
                  <CameraFeed
                    videoRef={mainCamera === "student" ? videoRef2 : videoRef1}
                    networkError={false}
                    type={mainCamera === "student" ? "content" : "student"}
                    isActive={true}
                    className="w-full h-full"
                    isPrimary={false}
                    pipMode={false}
                    onSwitchCamera={switchCameras}
                  />
                </div>
              </div>

              {/* ✅ 音频播放器放在主视频下方 */}
              <div className="mt-4">
                <AudioPlayer
                  url={audio_url}
                  isActive={audioActive}
                  onStatusChange={(status) => console.log("音频状态:", status)}
                />
              </div>
            </CardContent>
          </Card>
        </div>
      </CardContent>
    </Card>
  )
}
